package com.lognsoft.shell;

import java.util.ArrayList;

public class ShellCommandLine
{
	public final int type_internal = 1;
	public final int type_shell    = 2;

	String name = null;
	String full_name = null;
	String err_out = null;
	String std_out = null;
	ArrayList<String> args = null;
	int type = 0;
	ShellCommandLine NextPipe = null;
	ShellCommandLine NextGroup= null;

public static ShellCommandLine parse (String s)
{		
	ArrayList<String> args = null;
	
	ShellCommandLine root = null;
	ShellCommandLine last = null;
	String cmd;
	int len = s.length();
	
	/*
	 * replace " " format
	 * 
	 **/
	int ind = s.indexOf('\"');
	int from;
	
	if (ind < 0)
	{
		cmd = s;
	}
	else
	{
		StringBuffer cmdBuilder = new StringBuffer();
		
		for ( args = new ArrayList<String>(), from = 0; from < len && ind >=0; )
		{
			int indend = s.indexOf('\"',ind + 1);
			
			if (indend < 0 )
			{
				indend = s.length();
			}
			
			cmdBuilder.append(s.substring(from, ind));
			cmdBuilder.append('\"');
			cmdBuilder.append(args.size());
			
			args.add( s.substring(ind + 1, indend));
			
			from = indend + 1;			
			ind = s.indexOf('\"', from);
		}
		
		cmdBuilder.append('&');
		cmd = cmdBuilder.toString();
	}

	for (from = 0; from < len; )
	{
		ind = cmd.indexOf('&', from);
		ShellCommandLine scl = parsePipe(cmd.substring(from, ind), args);
		from = ind + 1;
		
		if (scl != null)
		{
			if (root == null)
			{
				root = scl;
				last = scl;
			}
			else
			{
				last.NextGroup = scl;
				last = scl;
			}			
		}
	}
	
	return root;
}

private static ShellCommandLine parsePipe(String s, ArrayList<String> args)
{
	if (s == null)
	{
		return null;
	}
	
	s = s.trim();
	
	if (s.length() == 0)
	{
		return null;
	}
	
	return null;
}

};